package com.itrip.controller;

import com.itrip.dto.OrderListDTO;
import com.itrip.dto.OrderPayDTO;
import com.itrip.dto.ResponseDTO;
import com.itrip.pojo.ItripHotelOrder;
import com.itrip.pojo.ItripUser;
import com.itrip.service.OrderService;
import com.itrip.vo.order.OrderAddVO;
import com.itrip.vo.order.OrderCountVO;
import com.itrip.vo.order.OrderListVO;
import io.swagger.annotations.*;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Api(tags = "订单相关接口")
@ApiResponses({
        @ApiResponse(code = 200, message = "请求正常", response = ResponseDTO.class)
})
@RestController
public class OrderController {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private OrderService orderService;

    /**
     * 根据token获取用户id信息
     */
    public Long getUserIdByToken(HttpServletRequest request){
        //根据token，获取用户id
        String token = request.getHeader("token");
        ItripUser user = (ItripUser) redisTemplate.opsForValue().get(token);
        return user.getId();
    }
     @ApiOperation("删除订单")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "token",value = "token令牌", dataType = "string", paramType = "header", required = true),
             @ApiImplicitParam(name = "id",value = "订单id", dataType = "long", required = true)
     })
     @DeleteMapping("/view/deleteOrderById")
    public ResponseDTO deleteOrderById(@RequestParam Long id){
        int count = orderService.deleteOrderById(id);
      return new ResponseDTO(100,"删除订单成功",count);
    }

    @ApiOperation("获取订单数量")
    @ApiImplicitParam(name = "token",value = "token令牌", dataType = "string", paramType = "header", required = true)
    @GetMapping("/view/getOrderCountByParams")
    public ResponseDTO getOrderCountByParams(OrderCountVO orderCountVO, HttpServletRequest request) {
        //根据token，获取用户id
        Long userId = getUserIdByToken(request);

        int count = orderService.getOrderCountByParams(orderCountVO, userId);

        return new ResponseDTO(100,"获取订单数量成功",count);
    }

    @ApiOperation("获取订单列表")
    @ApiImplicitParam(name = "token",value = "token令牌", dataType = "string", paramType = "header", required = true)
    @GetMapping("/view/getOrderListByParams")
    public ResponseDTO getOrderListByParams(OrderListVO orderListVO, HttpServletRequest request) {
        //根据token，获取用户id
        Long userId = getUserIdByToken(request);

        //查询分页起始行索引
        int start = (orderListVO.getPageNow()-1)*orderListVO.getPageSize();

        List<OrderListDTO> orderList = orderService.getOrderListByParams(orderListVO, userId, start);

        return new ResponseDTO(100,"查询订单列表成功",orderList);
    }

    @ApiOperation("获取订单支付信息")
    @ApiImplicitParam(name = "token",value = "token令牌", dataType = "string", paramType = "header", required = true)
    @GetMapping("/view/getOrderPayByUser")
    public ResponseDTO getOrderPayByUser(HttpServletRequest request) {
        //根据token，获取用户id
        Long userId = getUserIdByToken(request);

        OrderPayDTO orderPayDTO = orderService.getOrderPayByUser(userId);
        if(orderPayDTO != null){
            return new ResponseDTO(100,"查询成功",orderPayDTO);
        }
        return new ResponseDTO(101,"未查询到订单",null);
    }



    @ApiOperation("查询用户是否未支付的订单")
    @ApiImplicitParam(name = "token",value = "token令牌",dataType = "string",paramType = "header",required = true)
    @GetMapping("/view/getCountByUser")
    public ResponseDTO getCountByUser(HttpServletRequest request){
        Long userId = getUserIdByToken(request);



       int count = orderService.getCountByUser(userId);
        if(count > 0){
            return new ResponseDTO(101,"存在未支付的订单",null);
        }
        return new ResponseDTO(100,"账号下的订单状态正常",null);
    }


    @ApiOperation("添加订单")
    @ApiImplicitParam(name = "token",value = "token令牌", dataType = "string", paramType = "header", required = true)
    @PostMapping("/view/addOrder")
    public ResponseDTO addOrder(OrderAddVO orderAddVO, HttpServletRequest request) throws IOException, SolrServerException {
        //订单的创建-POJO
        ItripHotelOrder order = new ItripHotelOrder();

        //用户ID
        Long id = getUserIdByToken(request);
        //用户ID-POJO
        order.setUserId(id);

        //订单类型-POJO
        order.setOrderType(1);//酒店订单

        //订单号-纯数字，不能重复  时间戳后12位+6位房间ID(不足6位，0填充)
        //时间戳后12位
        long millis = System.currentTimeMillis();
        String s = Long.toString(millis);
        String prefix = s.substring(s.length()-12);

        //6位房间ID(不足6位，0填充)
        StringBuilder suffix = new StringBuilder(orderAddVO.getRoomId().toString());
        int sub = 6-suffix.length();
        if(sub > 0){
            for(int i=0; i<sub; i++){
                suffix.insert(0,"0");//往下标为0的位置添加字符串0
            }
        }
        //订单编号-POJO
        order.setOrderNo(prefix+suffix);

        //计算预订天数
        long time = orderAddVO.getCheckOutDate().getTime() - orderAddVO.getCheckInDate().getTime();
        int days = (int) (time/(1000*60*60*24));
        //预订天数-POJO
        order.setBookingDays(days);

        //订单类型-POJO
        order.setOrderType(1);//酒店订单

        //房间ID-POJO
        order.setRoomId(orderAddVO.getRoomId());
        //订房数量-POJO
        order.setCount(orderAddVO.getCount());
        //入住时间-POJO
        order.setCheckInDate(orderAddVO.getCheckInDate());
        //退房时间-POJO
        order.setCheckOutDate(orderAddVO.getCheckOutDate());
        //订单状态-POJO
        order.setOrderStatus(0);//未支付
        //支付金额-POJO
        order.setPayAmount(BigDecimal.valueOf(orderAddVO.getPayAmount()));
        //联系手机-POJO
        order.setNoticePhone(orderAddVO.getNoticePhone());
        //入住人-POJO
        order.setLinkUserName(orderAddVO.getLinkUserName());
        //操作位置
        order.setBookType(0);//WEB端
        //预订时间
        order.setCreationDate(new Date());

        //添加订单到数据库
        int count = orderService.addOrder(order);


        if(count > 0){
            return new ResponseDTO(100,"添加订单成功",order.getId());
        }
        return new ResponseDTO(101,"添加订单失败",null);
    }

}
